const arrNull = [undefined, null, '', 'undefined']
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
const timestampToTime = (timestamp) => {
    var date = new Date(parseInt(timestamp));
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
}
const checkIsNum = str => {
    if (typeof str === "string" || typeof str === "number") {
        let res = parseInt(str);
        if (res != str) {
            let res2 = parseFloat(str);
            if (res2 == str) {
                return true;
            }
            return false;
        }
    }
    return true;
}
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
}

const isInvalid = n => {
    let indexOf = arrNull.indexOf(n);
    //console.log(n, indexOf >= 0)
    return indexOf >= 0;
}

const fileToBase64 = (file, callback) => {
    wx.getFileSystemManager().readFile({
        filePath: file,//要读取的文件的路径 (本地路径)
        encoding: "base64",//指定读取文件的字符编码，如果不传 encoding，则以 ArrayBuffer 格式读取文件的二进制内容
        success: function (res) {
            let base64 = 'data:image/png;base64,' + res.data;
            //转换完毕，执行上传
            console.log(base64);
            callback(base64);
        }
    })
}

const fileToBase64Sync = (file) => {
    let index = file.lastIndexOf(".");
    let suffix = file.substring(index + 1, file.length);
    return "data:image/" + suffix + ";base64," + wx.getFileSystemManager().readFileSync(file, 'base64');
}

const getFromPage = (app, pages) => {
    let currentPage = pages[pages.length - 1];  //da当前页
    let prePath = app.$getFromPath(currentPage.route);
    if (!isInvalid(prePath)) {
        return prePath;
    }
    let prePage = pages[pages.length - 2];  //上一个页面
    prePath = "/" + prePage.route;
    app.$saveFromPath(currentPage.route, prePath);
    return prePath;
}


// 读取页面来的 url参数
const saveUrlParams = (app, options, skip) => {
    if (isInvalid(options)) {
        return;
    }
    for (const optionsKey in options) {
        if (skip.indexOf(optionsKey) >= 0) {
            continue;
        }
        let k = 'fromParams.' + optionsKey
        app.setData({
            [k]: options[optionsKey]
        })
    }
}

// 获取页面来的url参数
const getFromUrlParams = (app) => {
    let params = app.data.fromParams;
    let p = '?';
    if (!isInvalid(params)) {
        for (const paramsKey in params) {
            let val = params[paramsKey];
            if (!isInvalid(val)) {
                p += paramsKey + "=" + val + "&"
            }
        }
        return p.substring(0, p.length - 1);
    }
    return "";
}

const getEvent = (e) => {
    return e.currentTarget.dataset
}

/**
 * px 转 rpx
 * @param px 像素值
 */
const px2rpx = (px) => {
    const windowWidth = this.systemInfo.windowWidth;
    return 750 / windowWidth * px;
}

/**
 * rpx 转 px
 * @param rpx
 */
const rpx2px = (rpx) => {
    const windowWidth = this.systemInfo.windowWidth;
    return windowWidth / 750 * rpx;
}

const isInteger = (v) => {
    if (arrNull.indexOf(v) >= 0) {
        return false;
    }
    if (typeof v === "string" || typeof v === "number") {
        return v % 1 === 0;
    }
    return false;
}

// 获取年月日 周几
const getYmd_Week = () => {
    var date = new Date();
    var week = date.getDay();//获取星期
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    let weekStr = "";
    let tip = "上学日 😊";
    switch (week) {
        case 0:
            weekStr = "周日"
            tip = "休息日~ 😄"
            break;
        case 1:
            weekStr = "周一";
            break;
        case 2:
            weekStr = "周二";
            break;
        case 3:
            weekStr = "周三";
            break;
        case 4:
            weekStr = "周四";
            break;
        case 5:
            weekStr = "周五";
            break;
        case 6:
            weekStr = "周六";
            tip = "休息日~ 😄"
            break;
    }
    return year + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day) + "   " + weekStr + "(" + tip + ")"
}

const getUrlParams = (url) => {
    let index = url.indexOf("?");
    if (index < 0) {
        return null;
    }

    let params = url.substring(index + 1, url.length)

    if (isInvalid(params)) {
        return null;
    }

    let paramsArr = params.split("&");
    let obj = {};
    paramsArr.forEach(element => {
        let keyValueArr = element.split("=");
        obj[keyValueArr[0]] = keyValueArr[1]
    });
    return obj;
}

const paramsToPathParams = (params, path) => {
    let p = '?';
    if (!isInvalid(params)) {
        for (const paramsKey in params) {
            let val = params[paramsKey];
            if (!isInvalid(val)) {
                p += paramsKey + "=" + val + "&"
            }
        }
        return path + p.substring(0, p.length - 1);
    }
    return path;
}

module.exports = {
    formatTime
    , isInvalid
    , fileToBase64
    , getFromPage
    , saveUrlParams
    , getFromUrlParams
    , fileToBase64Sync
    , getYmd_Week
    , rpx2px
    , px2rpx
    , getEvent
    , isInteger
    , checkIsNum
    , getUrlParams
    , paramsToPathParams
    ,timestampToTime
}
